#include "sht30.h"
#include "gpio_iic.h"

void sht30_init(void)
{
	IIC_Init();
}

void set_repeat_mode(void)
{
	// 发送起始信号
	IIC_Start();
	IIC_Send_Byte(SHT_WRITE_ADDR);
	IIC_Wait_Ack();
	IIC_Send_Byte(REPEAT_CMD >> 8);
	IIC_Wait_Ack();
	IIC_Send_Byte(REPEAT_CMD & 0xff);
	IIC_Wait_Ack();
	
}

static void __set_fetch_mode(void)
{
	// 发送起始信号
	IIC_Start();
	IIC_Send_Byte(SHT_WRITE_ADDR);
	IIC_Wait_Ack();
	IIC_Send_Byte(FETCH_DATA >> 8);
	IIC_Wait_Ack();
	IIC_Send_Byte(FETCH_DATA & 0xff);
	IIC_Wait_Ack();
}

void sht30_read_data(double *temp, double *humi)
{
	u8 buf[6] = {0};
	u16 t, h;
	u8 i;
	
	// 设置采样频率
	//__set_repeat_mode();
	// 发送数据采集指令
	__set_fetch_mode();
	
	// 采集数据
	// 发送起始信号
	IIC_Start();
	IIC_Send_Byte(SHT_READ_ADDR);
	IIC_Wait_Ack();
	
	for (i = 0; i < 6; i++) {
		if (i < 5)
			buf[i] = IIC_Recv_Byte(1);
		else
			buf[i] = IIC_Recv_Byte(0);
	}
	
	IIC_Stop();
	// 公式转换
	t = (buf[0] << 8) | buf[1];
	h = (buf[3] << 8) | buf[4];
	
	*temp = (double)(-45 + 175 * ((double)t / (double)((1 << 16) - 1)));
	*humi = (double)(100 * ((double)h / (double)((1 << 16) - 1)));

}

